<template>
  <div class="father">
    
    <div class="pic">
      <p>招聘管理系统</p>
    
    </div>
    
    <div class="form">
      <div class="cont">
        <div class="title">
          <p>用户登录</p>
        </div>
        <el-form :model="form" :rules="rules" ref="loginform">
          <el-form-item prop="username">
            <el-input size="medium" v-model.trim="form.username" placeholder="用户名" ref="username"></el-input>
            <div class="el-form-item__error" v-if="nameerror">用户名错误</div>
          </el-form-item>
          <el-form-item prop="password">
            <el-input size="medium" type="password" v-model.trim="form.password" placeholder="密码"
                      @keyup.enter.native="onSubmit('loginform')"></el-input>
            <div class="el-form-item__error" v-if="passerror">密码错误</div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('loginform')" size="medium" round>登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="end">
              <el-col :span="12">
                <el-checkbox v-model="remname">记住用户名</el-checkbox>
              </el-col>
              <el-col :span="12" :offset="6">
                <el-checkbox v-model="rempass">记住密码</el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    
    </div>
    
    
    <!--  修改密码的弹出框-->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="400px"
      :before-close="addClose"
      class="addroledialog"
    >
      <div style="text-align: left">
        <div style="text-align: center;width: 100%;">
          <span style="color: red;">您的密码不符合规则，请修改后重新登录!</span>
        </div>
        
        <el-form label-position="top" :rules="rules1" ref="passform" :model="passform" style="padding:0px 50px;">
          <el-form-item prop="oldPassword" label="旧密码">
            <el-input placeholder="请输入旧密码" v-model.trim="passform.oldPassword" style="width: 274px"
                      type="password"></el-input>
            <div class="el-form-item__error" v-if="error2">旧密码输入错误</div>
          </el-form-item>
          <el-form-item prop="newPassword" label="新密码">
            <el-col>
              <el-input
                v-model.trim="passform.newPassword"
                placeholder="请输入新密码"
                style="width: 274px"
                type="password">
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item prop="renewpass" label="再次输入新密码">
            <el-col>
              <el-input
                v-model.trim="passform.renewpass"
                placeholder="请再次输入新密码"
                style="width: 274px"
                type="password"
              >
              </el-input>
              <div class="el-form-item__error" style="width: 100%;" v-if="error1">输入密码与新密码不相同</div>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
           <el-button class="sure" :disabled="senddis" round @click="send('passform')">确 定</el-button>
    <el-button round @click="cancel('passform')" class="cancel">取 消</el-button>
  </span>
    </el-dialog>
  
  </div>
</template>

<script>
  import Vue from 'vue'
  import Vuex from 'vuex'
  import axios from 'axios'
  import qs from 'qs'
  
  Vue.use(Vuex)
  
  import tagsView from '../../store/modules/tagsView'
  
  //校验密码
  var checkrepass = (rule, value, callback) => {
    var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,10}$/;
    
    if (!this.error1) {
      setTimeout(() => {
        if (value) {
          if (!re.test(value)) {
            callback(new Error('密码长度为6-10个字符，必须包含数字、大小写字母!'));
          } else {
            callback();
          }
        } else {
          callback()
        }
      }, 1000);
    }
  };
  
  export default {
    name: "login",
    data() {
      return {
        form: {
          username: '',
          password: ''
        },
        //用户名错误的提示变量
        nameerror: false,
        //密码错误的提示变量
        passerror: false,
        //登录表单的校验规则
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
          ]
        },
        //记住账号单选按钮绑定的变量
        remname: false,
        //记住密码单选按钮绑定的变量
        rempass: false,
        //修改密码的表单
        passform: {
          oldPassword: '',
          newPassword: '',
          renewpass: ''
        },
        //修改密码表单对应的校验
        rules1: {
          'oldPassword': [
            {required: true, message: '请输入旧密码', trigger: 'blur'},
            {min: 4, max: 12, message: '密码长度在4到12个字符', trigger: 'blur'}
          ],
          'newPassword': [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,10}$/, message: '密码长度为6-10个字符，必须包含数字、大小写字母!', trigger: 'blur'}
          ],
          'renewpass': [
            {required: true, message: '请输入新密码', trigger: 'blur'},
            {validator: checkrepass, trigger: 'blur'},
          ],
        },
        senddis: false,
        dialogVisible: false,
        error1: false,
        error2: false,
      }
    },
    created() {
      tagsView.dispatch('delAllViews');
      //判断是否有用户名以及密码的本地存储
      if (localStorage.getItem('username')) {
        this.form.username = localStorage.getItem('username')
        this.remname = true
      } else {
        this.remname = false
      }
      if (localStorage.getItem('password')) {
        this.form.password = localStorage.getItem('password')
        this.rempass = true
      } else {
        this.rempass = false
      }
    },
    methods: {
      //登录
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post(this.url + '/user/login', qs.stringify({
              username: this.form.username,
              password: this.form.password,
            })).then(res => {
              //用户名错误
              if (res.data.code == 201001) {
                this.nameerror = true
              }
              //密码错误
              if (res.data.code == 201002) {
                this.passerror = true
                this.nameerror = false
              }
              //密码过于简单
              if (res.data.code == -100) {
                this.dialogVisible = true;
                this.error2 = false;
                this.error1 = false;
                this.senddis = false;
                document.documentElement.style.overflow = 'hidden';
                this.passform = {
                  oldPassword: '',
                  newPassword: '',
                  renewpass: ''
                };
                this.$nextTick(() => {
                  this.$refs.passform.clearValidate();
                })
              }
              //正常
              if (res.data.code == 200) {
                this.nameerror = false
                this.passerror = false
                //本地存储用户名以及密码
                if (this.remname) {
                  localStorage.setItem('username', this.form.username)
                } else {
                  localStorage.removeItem('username')
                }
                if (this.rempass) {
                  localStorage.setItem('password', this.form.password)
                } else {
                  localStorage.removeItem('password')
                }
                //获取登录账户身份的不同,跳转不同的页面
                axios.post(this.url + '/user/getidentity').then(res => {
                  tagsView.commit('setIdentity', res.data.data)
                  if (res.data.data == 3 || res.data.data == 1 || res.data.data == 5 || res.data.data == 6) {
                    this.$router.push("/home/jobdemand")
                  } else if (res.data.data == 2) {
                    this.$router.push("/home/todaytaskleader")
                  } else if (res.data.data == 4) {
                    this.$router.push("/home/todaytask")
                  } else if (res.data.data == 7) {
                    this.$router.push("/home/interviewfeedback1")
                  } else if (res.data.data == 8) {
                    this.$router.push("/home/instorage")
                  } else if (res.data.data == 12 || res.data.data == 13) {
                    this.$router.push("/home/technicalInterview")
                  }
                })
                //修改vuex的状态
                tagsView.commit('changeLoginState', true)
              }
            })
          }
        });
        
      },
      //修改密码的弹出框
      addClose() {
        this.error2 = false;
        this.error1 = false;
        this.dialogVisible = false;
        document.documentElement.style.overflow = 'auto';
        this.senddis = false;
        this.$nextTick(() => {
          this.$refs.passform.clearValidate();
        })
      },
      //关闭修改密码的弹出框
      cancel(formName) {
        this.error2 = false;
        this.error1 = false;
        this.dialogVisible = false;
        this.senddis = false;
        document.documentElement.style.overflow = 'auto';
        this.$refs[formName].resetFields();
      },
      //发送修改密码的请求
      send(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.senddis = true;
            axios.post(this.url + '/user/updatepassword', qs.stringify(this.passform)).then(res => {
              this.unlogin(res.data.code);
              //旧密码错误
              if (res.data.code == -2) {
                this.error2 = true;
                this.senddis = false;
              } else {
                this.error2 = false;
                this.senddis = false;
              }
              //请求正常
              if (res.data.code == 200) {
                this.$message({
                  message: '密码修改成功，请重新登录!',
                  type: 'success'
                });
                this.passerror = false;
                this.nameerror = false;
                this.senddis = false;
                this.dialogVisible = false;
                this.error2 = false;
                this.error1 = false;
                this.senddis = false;
                document.documentElement.style.overflow = 'auto';
                this.$refs.loginform.resetFields();
              }
            })
          }
        })
      },
    },
    mounted() {
      this.$refs['username'].focus();
    },
    watch: {
      'passform.renewpass': function (val) {
        if (val && this.passform.newPassword !== '') {
          if (val !== this.passform.newPassword) {
            this.error1 = true;
          } else {
            this.error1 = false;
          }
        }
      },
      'passform.newPassword': function (val) {
        if (val && this.passform.renewpass !== '') {
          if (val !== this.passform.renewpass) {
            this.error1 = true;
          } else {
            this.error1 = false;
          }
        }
      },
    },
  }
</script>
<style scoped>
  
  .pic {
    width: 100%;
    height: 227px;
    background-color: #0073d3;
    position: absolute;
    top: 40%;
    transform: translateY(-50%);
    opacity: 0.8;
    line-height: 227px;
    font-size: 80px;
    color: #fff;
  }
  
  .pic > p {
    float: left;
    margin-left: 182px;
    letter-spacing: 4px;
  }
  
  .father > .form {
    width: 432px;
    height: 407px;
    float: left;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: #ccc 0px 0px 10px;
    z-index: 999;
    position: absolute;
    left: 57%;
    top: 40%;
    transform: translateY(-50%);
  }
  
  .cont {
    width: 348px;
    margin: 0 auto;
    margin-top: 35px;
  }
  
  .title {
    font-size: 22px;
    color: #333;
    margin-bottom: 40px;
  }
  
  .el-form {
    width: 320px;
    margin: 0 auto;
  }
  
  .father {
    width: 100%;
    height: 100%;
    position: absolute;
    background: url("../../../static/image/bg.png") no-repeat;
    background-size: 40% 100%;
  }
  
  .errorinfo {
    text-align: center;
    color: red;
  }
</style>
